package cn.juforg.airled;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources.NotFoundException;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

public class AirLED extends Activity {
	static String tagId = "Air_LED-";
	DisplayMetrics metric = new DisplayMetrics();
	int gridSize, gridCount, halfcount;
	private Paint paint = new Paint(); // 画笔对象
	private long scrollOffset = 0;
	AirView av = null;
	private Timer timer = null;
	private TimerTask refreshTask= null;
	private SensorManager sensorManager = null;   //感应器管理器
	private Sensor gravitySensor = null;		//重力感应器
	private SensorEventListener mySensorListener; //感应器监听器
	private RefreshHandler scroller = new RefreshHandler();
	SharedPreferences sp; 							//本应用配置信息
	static final int UPDATE_INTERVAL = 1000;		//重力感应检测间隔
	long mLastUpdateTime;						//上一次检测的时间
	

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// requestWindowFeature(ActivityInfo.SCREEN_ORIENTATION_SENSOR);//由物理感应器决定显示方向，它取决于用户如何持有设备
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);// 全屏显示
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		// Toast.makeText(AirLED.this, metric.widthPixels,
		// Toast.LENGTH_SHORT).show();
		// System.out.println("metric.xdpi"+metric.xdpi+"|widthPixels:"+metric.widthPixels+"|height:"+metric.heightPixels+"|density:"+metric.density+"|densityDpi:"+metric.densityDpi);
		//取得重力感应器对象
		sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		gravitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		
		if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
			//setTitle("x="+"x"+"y="+"y"+"z="+"z");
		}else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
			//setTitle("x="+"x"+"y="+"y"+"z="+"z");
		}
		mySensorListener = new SensorEventListener() {
			@Override
			public void onSensorChanged(SensorEvent event) {
				long currentTime = System.currentTimeMillis();
				long interval = currentTime - mLastUpdateTime;
				if (interval < UPDATE_INTERVAL) {
					return;
				}
				mLastUpdateTime = currentTime;
				float x = event.values[SensorManager.DATA_X];
				float y = event.values[SensorManager.DATA_Y];
				float z = event.values[SensorManager.DATA_Z];
				Toast.makeText(AirLED.this, "x:"+x+";y:"+y+";z:"+z,Toast.LENGTH_SHORT).show();
//				setTitle("x="+x+"y="+y+"z="+z);
			}
			
			@Override
			public void onAccuracyChanged(Sensor sensor, int accuracy) {
				
			}
		};
		//取得格子大小
		gridSize = getResources().getDrawable(R.drawable.led_cell).getIntrinsicHeight();
		
		//创建字体文件
		createFontFile();

		try {
			av = new AirView(this, 16, "依然爱你！", metric, paint, getResources().getDrawable(R.drawable.led_cell),getFileStreamPath("hzk16"));
		} catch (UnsupportedEncodingException e1) {
			Log.e(tagId, e1.getMessage());
			e1.printStackTrace();
		} catch (NotFoundException e2) {
			Log.e(tagId, e2.getMessage());
			e2.printStackTrace();
		} catch (IOException e) {
			Log.e(tagId, e.getMessage());
			e.printStackTrace();
		}
//		scroller = new RefreshHandler();
		gridCount = metric.widthPixels / gridSize;
		halfcount = (gridCount & 1) == 0 ? gridCount / 2
				: (gridCount - gridSize) / 2 + 1;
		setContentView(av);
//		this.scroller.startScroll(100);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu paramMenu) {
		new MenuInflater(this).inflate(R.menu.mainmenu, paramMenu);
		return super.onCreateOptionsMenu(paramMenu);
	}
	
	public void refreshConfig(AirView av,SharedPreferences sp){
		av.text = sp.getString("Text", getResources().getString(R.string.settings_speed_summary));
		String color = sp.getString("TextColor", getResources().getString(R.string.settings_textcolor_white));
		if (color == getResources().getString(R.string.settings_textcolor_white)) {
			
		}else if (color == getResources().getString(R.string.settings_textcolor_white)) {
			av.textPaint.setColor(Color.WHITE);
		}else if (color == getResources().getString(R.string.settings_textcolor_blue)){
			av.textPaint.setColor(Color.BLUE);
		}else if (color == getResources().getString(R.string.settings_textcolor_green)){
			av.textPaint.setColor(Color.GREEN);
		}else if (color == getResources().getString(R.string.settings_textcolor_red)){
			av.textPaint.setColor(Color.RED);
		}
		try {
//			av.getMatrixByteList(av.text);
//			av.genActualMatrixShortList();
			av.init();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem paramMenuItem) {
		boolean bool;
		switch (paramMenuItem.getItemId()) {
		default:
			bool = super.onOptionsItemSelected(paramMenuItem);
			break;
		case R.id.menu_settings:
			startActivityForResult(new Intent(this, Settings.class), 1);
			bool = true;
		}
		return bool;
	}


	/**
	 * 在程序第一次运行时就把apk中的字库文件hzk16写到ram或sd卡中
	 * 
	 * @return
	 */
	public boolean createFontFile() {
		File file = getFileStreamPath("hzk16");
		if (!file.exists()) {
			byte readBuff[] = new byte[1024];
			InputStream is = null;
			FileOutputStream outStream;
			try {
				outStream = this.openFileOutput("hzk16", Context.MODE_PRIVATE);
				is = getResources().openRawResource(R.raw.hzk16);
				int length = -1;
				while ((length = is.read(readBuff)) != -1) {
					outStream.write(readBuff);
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return false;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	/**
	 * 
	 * @param speed
	 */
	private void startTimer(int speed) {
		this.timer = new Timer();
		final Runnable runnable = new Runnable() {
			public void run() {
//				av.refreshScreenMatrix(scrollOffset, 1);
//				scroller.startScroll(speed);
//				AirLED.this.av.invalidate();
				AirLED.this.av.repaint();
			}
		};
		this.refreshTask = new TimerTask() {
			@Override
			public void run() {
//				AirLED.this.runOnUiThread(runnable);
				Log.i(tagId, "scrollOffset:"+scrollOffset);
				if (av.isRun) {
					
//				av.refreshScreenMatrix(scrollOffset, 1);
				av.processCmd(scrollOffset, 1);
//				scroller.startScroll(speed);
//				scroller.post(runnable);
//				scrollOffset = (metric.widthPixels/(metric.heightPixels/16))%(1L + scrollOffset);
				scrollOffset = 1L + scrollOffset;
				}
			}
		};
		this.timer.schedule(refreshTask, 1000L,speed);
	}

	@Override
	protected void onPause() {
		//注销监听器
		sensorManager.unregisterListener(mySensorListener);
		Log.i(tagId, "onPause:unregisterListner");
		this.refreshTask.cancel();
		this.refreshTask = null;
		this.timer.cancel();
		this.timer.purge();
		this.timer = null;
		super.onPause();
	}

	@Override
	protected void onResume() {
		//注册监听器
		sensorManager.registerListener(mySensorListener, gravitySensor, SensorManager.SENSOR_DELAY_GAME);
		Log.i(tagId, "onResume:registerListner");
		refreshConfig(av, PreferenceManager.getDefaultSharedPreferences(this));
		startTimer(100);
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	class RefreshHandler extends Handler {
		//这个方法主要在指定的时刻发一个消息
        public void startScroll(long delayMillis) {
//        	while (true) {
        	this.removeMessages(0);
        	//计算屏幕数组内值
        	av.refreshScreenMatrix(scrollOffset, 1);
        	//发消息触发handleMessage函数
            sendMessage(obtainMessage(0));
//            sendMessageDelayed(obtainMessage(0), delayMillis);
//        	}
        }
        
        //收到消息
        @Override
        public void handleMessage(Message msg) {
    		//刷新一下
        	AirLED.this.av.postInvalidate();
//        	scrollOffset = 1L + scrollOffset;
        	super.handleMessage(msg);
        }
    }
	
}